import axios from "axios";
import { Message } from "element-ui";

//axios实例
const instance = axios.create({
  withCredentials: true,
  baseURL: 'https://www.snmake.com:8080',
  // baseURL: 'http://localhost:9998',
  timeout: 60000
})

var username = localStorage.getItem("username");
if(username)
// 请求拦截器
//   'username':  (localStorage.getItem("username") == undefined ||localStorage.getItem("username") == "")   ? undefined: localStorage.getItem("username"),
instance.interceptors.request.use(config => {
  config.data = JSON.stringify(config.data);
  config.headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'username' : undefined,
    'X-Token': (localStorage.getItem("token") == undefined ||localStorage.getItem("token") == "")   ? undefined: localStorage.getItem("token")
  }
  return config;
},error => {
  Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response => {
  if(response.status === 200) {
    if(response.data.code === 20000) {
      return response;
    }else {
      Message.error(response.data.message);
      return response;
    }
  }else {
    Message.error(response.message);
    return reject(response);
  }
},error => {
  const err = error.toString()
  if(err == 'Error: Network Error') {
    Message.error("网络出现问题，请检查网络是否连接！")
  }else if(err == 'Error: timeout of 30000ms exceeded') {
    Message.error("网络连接超时，请重新加载！")
  }else {
    Message.error(err)
  }
  return Promise.resolve(error)
})

export default instance;

